<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 4] Expressions</TITLE>
<META NAME="author" CONTENT="Mark Grand">
<META NAME="date" CONTENT="Thu Jul 31 13:09:41 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="java">
<META NAME="title" CONTENT="Java Language Reference">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">
<script language='JavaScript'>
<!--
if (location.replace) {
 location.replace ('ch04_js.htm');
}
// -->
</script>

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Java Language Reference" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch03_02.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 4</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch04_02.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<H1 CLASS=chapter><A CLASS="TITLE" NAME="JLR2-CH-4">4. Expressions</A></H1>

<DIV CLASS=htmltoc>

<p>
<b>Contents:</b><br>
<a href='ch04_02.htm'>Allocation Expressions</a><br>
<a href='ch04_03.htm'>Increment/Decrement Operators</a><br>
<a href='ch04_04.htm'>Unary Operators</a><br>
<a href='ch04_05.htm'>Multiplicative Operators</a><br>
<a href='ch04_06.htm'>Additive Operators</a><br>
<a href='ch04_07.htm'>Shift Operators</a><br>
<a href='ch04_08.htm'>Relational Comparison Operators</a><br>
<a href='ch04_09.htm'>Equality Comparison Operators</a><br>
<a href='ch04_10.htm'>Bitwise/Logical Operators</a><br>
<a href='ch04_11.htm'>Boolean Operators</a><br>
<a href='ch04_12.htm'>Conditional Operator</a><br>
<a href='ch04_13.htm'>Assignment Operators</a><br>
<a href='ch04_14.htm'>Order of Operations</a><br>
<a href='ch04_15.htm'>Data Type of an Expression</a><br>
<a href='ch04_16.htm'>Constant Expressions</a><br>
<p>
<p>
</DIV>

<P CLASS=para>
Expressions
in Java are used to fetch, compute, and store values. To fetch a
value, you use a type of expression called a primary expression.
To compute and store values, you use the various operators described
in this chapter. In Java, expressions are most often used in methods
and constructors; they can also appear in field variable initializers
and static initializers.

<P CLASS=para>
Most expressions, when they
are evaluated, produce values that can be used by other expressions.
The one exception is an expression that calls a method declared
with the <tt CLASS=literal>void</tt> return type. An expression that
invokes a <tt CLASS=literal>void</tt> method cannot be embedded in another
expression. The evaluation of an expression can also produce side
effects, such as variable assignments and increment and decrement
operations.

<P CLASS=para>
The value produced by an expression can
be either a pure value or a variable
or array element. The distinction is that a <I CLASS=emphasis>pure value</I>
cannot be used to store a value, while a variable or array element
can.[1]
An expression that produces a variable or an array element can be
used anywhere that an expression that produces a pure value can
be used.

<blockquote class=footnote>
<P CLASS=para>[1] 
Note that Java's distinction between pure values
and variable and array elements is similar to the distinction in
C and C++ between rvalues and lvalues.
</blockquote>
<P CLASS=para>
This chapter refers to values as being either
pure values or variables.
Saying that a value is a pure value means that it is a value such
as 24 that contains information, but cannot be used as the target
of an assignment expression. Saying that a value is a variable means
that it is something like <tt CLASS=literal>var</tt> or <tt CLASS=literal>ar[i]</tt>
that can be used as the target of an assignment. The generic term
"value" is used to mean either a variable or a pure value.

<P CLASS=para>
The
formal definition of an expression is:


<p>
<img align=middle src="./figs/jlr0401.gif" alt="[Graphic: Figure from the text]" width=424 height=27 border=0>

<P CLASS=para>
The above diagram may seem
deceptively simple; why is such a definition even necessary? Expressions
in Java are defined with a number of mutually recursive railroad
diagrams. You can think of the <I CLASS=emphasis>Expression</I> definition
as being both the lowest-level definition and the highest-level
definition of these mutually recursive diagrams. In other words,
<tt CLASS=literal>a=b[i]+c[i]</tt> is an expression, as are <tt CLASS=literal>b[i]</tt>,
<tt CLASS=literal>c[i]</tt>, <tt CLASS=literal>a</tt>, <tt CLASS=literal>b</tt>,
<tt CLASS=literal>c</tt>, and <tt CLASS=literal>i</tt>. This first diagram
defines an expression to be an <I CLASS=emphasis>AssignmentExpression</I>,
which is the final definition used to describe Java expressions.

<P CLASS=para>
<b>References</b>
<A HREF="ch04_13.htm#JLR2-CH-4-SECT-13">Assignment Operators</A>

<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-1">4.1 Primary Expressions</A></h2>

<P CLASS=para>
<A NAME="CH04.PRIM1"></A>A primary expression
is the most elementary type of expression. Primary expressions are
constructs that fetch or create values, but do not directly perform
computations on them:


<p>
<img align=middle src="./figs/jlr0402.gif" alt="[Graphic: Figure from the text]" width=424 height=50 border=0>

<P CLASS=para>
<I CLASS=emphasis>Terms</I> are those primary expressions that produce values, 
by doing such things as accessing fields in classes, invoking methods, and accessing
array elements:


<p>
<img align=middle src="./figs/jlr0403.gif" alt="[Graphic: Figure from the text]" width=424 height=198 border=0>

<P CLASS=para>
<b>References</b>
<A HREF="ch04_02.htm#JLR2-CH-4-SECT-2">Allocation Expressions</A>;
<I CLASS=emphasis>Expression</I> 4;
<I CLASS=emphasis>FieldExpression</I> 4.1.6;
<A HREF="ch02_02.htm#JLR2-CH-2-SECT-2.1">Identifiers</A>;
<A HREF="ch04_01.htm#JLR2-CH-4-SECT-1.7">Index Expressions</A>;
<A HREF="ch02_02.htm#JLR2-CH-2-SECT-2.3">Literals</A>;
<A HREF="ch04_01.htm#JLR2-CH-4-SECT-1.8">Method Call Expression</A>;
<A HREF="ch04_01.htm#JLR2-CH-4-SECT-1.9">Class Literals</A>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-1.1">this</A></h3>

<P CLASS=para>
<A NAME="CH04.THIS"></A>The keyword <tt CLASS=literal>this</tt>
can be used only in the body of a constructor or an instance method
(i.e., a method that is not declared <tt CLASS=literal>static</tt>),
or in the initializer for an instance variable. A <tt CLASS=literal>static</tt>
method is not associated with an object, so <tt CLASS=literal>this</tt>
makes no sense in such a method and is treated as an undefined variable.
If <tt CLASS=literal>this</tt> is used in an inappropriate place, a
compile-time error occurs.

<P CLASS=para>
The value produced by <tt CLASS=literal>this</tt>
is a reference to the object associated with the expression that
is being evaluated. The type of the primary expression <tt CLASS=literal>this</tt>
is a reference to the class in which it appears.

<P CLASS=para>
One common use for <tt CLASS=literal>this</tt> is to allow
access to a field variable when there is a local variable with
the same name. For example:

<DIV CLASS=screen>
<P>
<PRE>
int foo;
void setFoo(int foo) {
    this.foo = foo;
}
</PRE>
</DIV>

<P CLASS=para>
Another 
common usage is to implement a callback mechanism. Passing <tt CLASS=literal>this</tt>
to another object allows that object to call methods in the object
associated with the calling code. For example, to allow an object
inside of an applet to be able to access parameters passed to the
applet in the HTML <tt CLASS=literal>&lt;applet&gt;</tt> tag, you can
use code like the following:

<DIV CLASS=screen>
<P>
<PRE>
public class MyApplet extends Applet {
    ...
    Foo foo;
    public void init() {
        foo = new Foo(this);
    ...
    }
}
class Foo {
    Applet app;
    ...
    Foo(Applet app) {
        this.app = app;
    }
    ...
    void doIt() {
        String dir = app.getParameter("direction");
        ...
    }
    ...
}
</PRE>
</DIV>

<P CLASS=para>
Another use for the keyword <tt CLASS=literal>this</tt> is 
in a special kind of <I CLASS=emphasis>FieldExpression</I> that 
refers to an enclosing instance of this
object. A reference to an enclosing instance is written as the
class name of the enclosing instance followed by a dot and the keyword
<tt CLASS=literal>this</tt> (as described in 5.3.7.2 Member classes). Consider the following code:

<DIV CLASS=screen>
<P>
<PRE>
public class ImageButton extends Canvas {
    ...
    private class MyImage extends Image {
        Image fileImage;
        MyImage(String fileName) throws IOException {
            URL url = new URL(fileName);
            ImageProducer src = (ImageProducer)url.getContent();
            Image fileImage = createImage(src);
            prepareImage(this, ImageButton.this);
        } 
    ...
</PRE>
</DIV>

<P CLASS=para>
The call to <tt CLASS=literal>prepareImage()</tt> takes 
two arguments. The first argument
is a reference to <tt CLASS=literal>this</tt> instance of the 
<tt CLASS=literal>MyImage</tt> class. The second
argument is a reference to this object's enclosing instance, which
is an instance of the <tt CLASS=literal>ImageButton</tt> class.

<P CLASS=para>
<b>References</b>
<A HREF="ch05_04.htm#JLR2-CH-5-SECT-4.4.3">Constructors</A>;
<A HREF="ch05_04.htm#JLR2-CH-5-SECT-4.4.3.6">Constructor implementation</A>;
<I CLASS=emphasis>FieldExpression</I> 4.1.6;
<A HREF="ch05_03.htm#JLR2-CH-5-SECT-3.7">Inner Classes</A>;
<A HREF="ch05_04.htm#JLR2-CH-5-SECT-4.4.2">Methods</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-1.2">super</A></h3>

<P CLASS=para>
The keyword <tt CLASS=literal>super</tt>
can be used only in the body of a constructor or an instance method
(i.e., a method that is not declared <tt CLASS=literal>static</tt>),
or in the initializer for an instance variable. In addition, <tt CLASS=literal>super</tt>
cannot appear in the class <tt CLASS=literal>Object</tt> because <tt CLASS=literal>Object</tt>
has no superclass. If <tt CLASS=literal>super</tt> is used in an inappropriate
place, a compile-time error occurs.

<P CLASS=para>
In most cases, the
primary expression <tt CLASS=literal>super</tt> has a value that is
equivalent to casting the value of the primary expression <tt CLASS=literal>this</tt>
to the superclass of the class in which it appears. In other words,
<tt CLASS=literal>super</tt> causes the object to be treated as an instance
of its superclass. The type of the primary expression <tt CLASS=literal>super</tt>
is a reference to the superclass of the class in which it appears.

<P CLASS=para>
There are two situations in which <tt CLASS=literal>super</tt>
produces a result that is different than what would be produced
by casting <tt CLASS=literal>this</tt> to its superclass:

<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>When <tt CLASS=literal>super</tt> is used to explicitly call a constructor
in the superclass from a constructor in the class, the field variables
for the class are initialized when the superclass's constructor returns.

<P>
<li CLASS=listitem>If a class contains a method that overrides a method declared
in its superclass, calling the method by casting <tt CLASS=literal>this</tt>
to the superclass results in a call to the overriding method. However,
calling the method with the special reference provided by
<tt CLASS=literal>super</tt> calls the overridden method in the superclass.

<P>
</UL>
<P CLASS=para>
The main purpose of <tt CLASS=literal>super</tt> is to allow the behavior of
methods and constructors to be extended, rather than having to be totally
replaced. Consider the following example:

<DIV CLASS=screen>
<P>
<PRE>
class A {
    public int foo(int x) {
        return x*x;
    }
    public int bar(int x) {
        return x*8;
    }
}
class B extends A{
    public int foo(int x) {
        return super.foo(x)+x;
    }
    public int bar(int x){
        return x*5;
    }
}
</PRE>
</DIV>

<P CLASS=para>
The <tt CLASS=literal>foo()</tt>
method in class <tt CLASS=literal>B</tt> extends the behavior of the
<tt CLASS=literal>foo()</tt> method in class <tt CLASS=literal>A</tt> by
calling that method and performing further computations on its result.
On the other hand, the <tt CLASS=literal>bar()</tt> method in class
<tt CLASS=literal>B</tt> totally replaces the behavior of the <tt CLASS=literal>bar()</tt>
method in class <tt CLASS=literal>A</tt>.

<P CLASS=para>
<b>References</b>
<A HREF="ch05_04.htm#JLR2-CH-5-SECT-4.4.3">Constructors</A>;
<A HREF="ch05_04.htm#JLR2-CH-5-SECT-4.4.3.6">Constructor implementation</A>;
<A HREF="ch05_04.htm#JLR2-CH-5-SECT-4.4.2">Methods</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-1.3">null</A></h3>

<P CLASS=para>
The primary expression <tt CLASS=literal>null</tt>
produces a special object reference value that does not refer to
any object, but is assignment-compatible with all object reference
types.

<P CLASS=para>
An operation on an object reference that does
not attempt to access the referenced object works the same way for
<tt CLASS=literal>null</tt> as it does for other object reference values.
For example:

<DIV CLASS=screen>
<P>
<PRE>
foo == null
</PRE>
</DIV>

<P CLASS=para>
However, any operation
that attempts to access an object through a <tt CLASS=literal>null</tt>
reference throws a <tt CLASS=literal>NullPointerException</tt>. The
one exception to this rule is the string concatenation operator
(<tt CLASS=literal>+</tt>), which converts a <tt CLASS=literal>null</tt>
operand to the string literal <tt CLASS=literal>"null"</tt>.

<P CLASS=para>
<b>References</b>
<A HREF="ch09_04.htm#JLR2-CH-9-SECT-4.1.1">Runtime exceptions</A>;
<A HREF="ch04_06.htm#JLR2-CH-4-SECT-6.3">String Concatenation Operator +</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-1.4">Literal Expressions</A></h3>

<P CLASS=para>
A primary expression
that consists of a literal produces a pure value. The data type
of this pure value is the data type of the literal.

<P CLASS=para>
<b>References</b>
<A HREF="ch02_02.htm#JLR2-CH-2-SECT-2.3">Literals</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-1.5">Parenthetical Expressions</A></h3>

<P CLASS=para>
A primary expression
that consists of a parenthesized expression
produces the same pure value as the expression in parentheses. The
data type of this pure value is also the same as the data type of
the expression in parentheses. A parenthetical expression can only
produce a pure value. Thus, the following code produces an error:

<DIV CLASS=screen>
<P>
<PRE>
(x) = 5;          // Illegal
</PRE>
</DIV>

<P CLASS=para>
<b>References</b>
<I CLASS=emphasis>Expression</I> 4

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-1.6">Field Expressions</A></h3>

<P CLASS=para>
<A NAME="CH04.FIELD2"></A><A NAME="CH04.FIELD1"></A>A <I CLASS=emphasis>field expression</I>
is a primary expression that fetches such things as local variables,
formal parameters, and field variables. A field expression can evaluate
to a pure value or a variable. The data type of a field expression
is the data type of the pure value, variable, or array element produced
by the following expression.


<p>
<img align=middle src="./figs/jlr0404.gif" alt="[Graphic: Figure from the text]" width=424 height=73 border=0>


<p>
<img align=middle src="./figs/jlr0405.gif" alt="[Graphic: Figure from the text]" width=424 height=52 border=0>

<P CLASS=para>
Essentially, a field expression
can be a simple identifier, a primary expression followed by an
identifier, or a class or interface name followed by an identifier.
Here's an example of a field expression that consists of a simple
<I CLASS=emphasis>Identifier</I> :

<DIV CLASS=screen>
<P>
<PRE>
myVar
</PRE>
</DIV>

<P CLASS=para>
Before the Java compiler
can decide what to do with a lone identifier
such as this, it must first match it with a declaration. The compiler
first looks in the method where the identifier appears for a local
variable or formal parameter with the same name as the identifier.
If the compiler finds a matching local variable or formal parameter,
the field expression produces the matching variable or parameter.

<P CLASS=para>
If the identifier does not match a local variable or a formal
parameter, it is expected to match the name of a field variable
in the class in which it occurs. 

<P CLASS=para>
If the matching variable is declared
<tt CLASS=literal>final</tt>, the field expression produces the pure
value specified by the variable's initializer. Otherwise, the field
expression produces the matching field variable. If the method that
the identifier appears in is declared <tt CLASS=literal>static</tt>,
the matching variable must also be declared <tt CLASS=literal>static</tt>
or the compiler declares an error.

<P CLASS=para>
A lone identifier that matches the name of a field variable is equivalent
to:

<DIV CLASS=screen>
<P>
<PRE>
this.Identifier
</PRE>
</DIV>

<P CLASS=para>
This form of a field expression can be used to access a field
variable that is shadowed by a local variable or a formal parameter.
For example:

<DIV CLASS=screen>
<P>
<PRE>
class Shadow {
    int value;
    Shadow(int value) {
        this.value=value;
    }
}
</PRE>
</DIV>

<P CLASS=para>
In the above example,
the identifier <tt CLASS=literal>value</tt> is used as both the name
of a field variable and the name of a formal parameter in the constructor.
Within the constructor, the unqualified identifier <tt CLASS=literal>value</tt>
refers to the formal parameter, not to the field variable. In order
to access the field variable, you have to qualify <tt CLASS=literal>value</tt>
with <tt CLASS=literal>this</tt>.

<P CLASS=para>
In addition to allowing an object to refer to itself, the keyword 
<tt CLASS=literal>this</tt> has another use in field expressions. 
The construct 
<I CLASS=emphasis>ClassOrInterfaceName</I><tt CLASS=literal>.this</tt>
identifies the enclosing instance of an object that is an 
instance of an inner class.[2]
Consider the following
example:

<blockquote class=footnote>
<P CLASS=para>[2] 
Since this construct
fetches an object reference, you might expect it to be a
primary expression. However, due to the way in which
inner classes are implemented, this construct is actually a 
field expression.
</blockquote>
<DIV CLASS=screen>
<P>
<PRE>
public class ImageButton extends Canvas {
    ...
    private class MyImage extends Image {
        Image fileImage;
        MyImage(String fileName) throws IOException {
            URL url = new URL(fileName);
            ImageProducer src = (ImageProducer)url.getContent();
            Image fileImage = createImage(src);
            prepareImage(this, ImageButton.this);
        } 
    ...
</PRE>
</DIV>

<P CLASS=para>
The call to <tt CLASS=literal>prepareImage()</tt> takes 
two arguments. The first argument
is a reference to <tt CLASS=literal>this</tt> instance of the 
<tt CLASS=literal>MyImage</tt> class. The second
argument is a reference to this object's enclosing instance, which
is an instance of the <tt CLASS=literal>ImageButton</tt> class.

<P CLASS=para>
Here are some examples
of field expressions that consist of a <I CLASS=emphasis>PrimaryExpression</I>
and an <I CLASS=emphasis>Identifier</I>:

<DIV CLASS=screen>
<P>
<PRE>
this.myVar
size().height
(new Foo()).bar
</PRE>
</DIV>

<P CLASS=para>
A primary expression that appears at the beginning of a field expression must
produce a reference to an object. The identifier to the right of
the dot must be the name of a field variable in the object referred
to by the primary expression. If, at runtime, the primary expression
in a field expression produces the value <tt CLASS=literal>null</tt>,
a <tt CLASS=literal>NullPointerException</tt> is thrown.

<P CLASS=para>
Here's an example of a field expression that
consists of a <I CLASS=emphasis>ClassOrInterfaceName</I>
and an <I CLASS=emphasis>Identifier</I>:

<DIV CLASS=screen>
<P>
<PRE>
Double.POSITIVE_INFINITY
</PRE>
</DIV>

<P CLASS=para>
A field expression that begins with <I CLASS=emphasis>ClassOrInterfaceName</I>
produces a field variable of the specified class. If the field variable
is not declared <tt CLASS=literal>static</tt>, the specified class must
either be the same class in which the field expression appears or
a superclass of that class.

<P CLASS=para>
Such a field expression is approximately
equivalent to:

<DIV CLASS=screen>
<P>
<PRE>
((ClassOrInterfaceName)this).Identifier
</PRE>
</DIV>

<P CLASS=para>
If <I CLASS=emphasis>ClassOrInterfaceName</I> specifies a class
or interface defined in a different package than the package in
which the field expression appears, the class name must be qualified
by the package in which the class is defined. For example:

<DIV CLASS=screen>
<P>
<PRE>
java.awt.Event.MOUSE_UP
</PRE>
</DIV>

<P CLASS=para>
However,
if an import statement imports the specified class, the package
name is not necessary.

<P CLASS=para>
<I CLASS=emphasis>ClassOrInterfaceName</I> can refer to an 
inner class or a nested top-level class or
interface by qualifying the name of the class or interface with the
name of the enclosing class. For example, consider the following
declaration:

<DIV CLASS=screen>
<P>
<PRE>
public class A {
    public class B {
    } 
}
</PRE>
</DIV>

<P CLASS=para>
Based on this declaration, you can create a new instance of
<tt CLASS=literal>B</tt> as follows:

<DIV CLASS=screen>
<P>
<PRE>
new A.B()
</PRE>
</DIV>

<P CLASS=para>
Most field expressions produce
variables when they are evaluated. This means that the field expression
can be used as the left operand of an assignment operator. A field
expression produces a pure value, rather than a variable, if the
identifier at the end of the field expression is a field variable
that is declared <tt CLASS=literal>final</tt>.
Such a field expression returns a pure value because the value of
a <tt CLASS=literal>final</tt> variable cannot be modified. A field
expression that produces a pure value cannot be the left operand
of an assignment operator, or the operand of the <tt CLASS=literal>++</tt>
or <tt CLASS=literal>- -</tt> operators. Here's an erroneous example:

<DIV CLASS=screen>
<P>
<PRE>
final int four=4
four++
</PRE>
</DIV>

<P CLASS=para>
This is equivalent to:

<DIV CLASS=screen>
<P>
<PRE>
4++
</PRE>
</DIV>

<P CLASS=para>
As such, it causes the
Java compiler to issue an error message.

<P CLASS=para>
When the Java
compiler detects an expression that uses the value of a local variable
that may not have been initialized, it issues an error message.
For example:

<DIV CLASS=screen>
<P>
<PRE>
{
    int x;
    if (testForSomething())
        x = 4;
    System.out.println(x);    // Compiler complains
}
</PRE>
</DIV>

<P CLASS=para>
The compiler complains
about the use of <tt CLASS=literal>x</tt> in the <tt CLASS=literal>println()</tt>
method because <tt CLASS=literal>x</tt> may not have been given an explicit
value when the program reaches
that statement. Even though there is an assignment to <tt CLASS=literal>x</tt>
in the preceding statement, the compiler recognizes that the assignment
may not have been performed, since it is enclosed within a conditional
statement. The Java language specification requires that a compiler
issue an error message when it detects an uninitialized local variable.

<P CLASS=para>
<b>References</b>
<A HREF="ch02_02.htm#JLR2-CH-2-SECT-2.1">Identifiers</A>;
<A HREF="ch05_03.htm#JLR2-CH-5-SECT-3.5">Inheritance</A>;
<A HREF="ch05_03.htm#JLR2-CH-5-SECT-3.7">Inner Classes</A>;
<A HREF="ch05_05.htm#JLR2-CH-5-SECT-5.4.1">Interface Variables</A>;
<A HREF="ch06_01.htm#JLR2-CH-6-SECT-1.1">Local Variables</A>;
<A HREF="ch07_02.htm#JLR2-CH-7-SECT-2">Packages</A>;
<A HREF="ch04_01.htm#JLR2-CH-4-SECT-1">Primary Expressions</A>;
<A HREF="ch09_04.htm#JLR2-CH-9-SECT-4.1.1">Runtime exceptions</A>;
<A HREF="ch05_04.htm#JLR2-CH-5-SECT-4.4.1">Variables</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-1.7">Index Expressions</A></h3>

<P CLASS=para>
An <I CLASS=emphasis>index expression</I>
is a primary expression that produces an array element when it is
evaluated. The value produced by an index expression is a variable;
it can be used as the left operand of an assignment expression.
The data type of an index expression is the data type of the array
element produced by the expression:


<p>
<img align=middle src="./figs/jlr0406.gif" alt="[Graphic: Figure from the text]" width=450 height=32 border=0>

<P CLASS=para>
When the compiler
evaluates an index expression, the term to the left of the square
brackets is evaluated before the expression inside of the square
brackets. If the term produces the value <tt CLASS=literal>null</tt>,
a <tt CLASS=literal>NullPointerException</tt>
is thrown.

<P CLASS=para>
Array indexing uses an <tt CLASS=literal>int</tt>-valued
expression between the square brackets. If the type of the expression
is <tt CLASS=literal>byte</tt>, <tt CLASS=literal>char</tt>, or <tt CLASS=literal>short</tt>,
the value is automatically converted to <tt CLASS=literal>int</tt>.
An array index cannot be of type <tt CLASS=literal>long</tt>. The value
of the array index must be in the range zero to one less than the
length of the array. An array object detects an out-of-range index
value and throws an <tt CLASS=literal>ArrayIndexOutOfBoundsException</tt>.

<P CLASS=para>
Because of the precedence of Java expressions, an array allocation
expression can only be indexed when the expression is enclosed in
parentheses. For example:

<DIV CLASS=screen>
<P>
<PRE>
(new int[6])[3]
</PRE>
</DIV>

<P CLASS=para>
This expression
refers to the fourth element of the newly created array. Leaving
out the parentheses results in the following:

<DIV CLASS=screen>
<P>
<PRE>
new int[6][3]
</PRE>
</DIV>

<P CLASS=para>
This is not an
index expression, but an array allocation expression that allocates
an array of 3 arrays of 6 integers.

<P CLASS=para>
<b>References</b>
<A HREF="ch04_02.htm#JLR2-CH-4-SECT-2.2">Array Allocation Expressions</A>;
<A HREF="ch03_02.htm#JLR2-CH-3-SECT-2.3">Array Types</A>;
<I CLASS=emphasis>Expression</I> 4;
<I CLASS=emphasis>Term</I> 4.1;
<A HREF="ch09_04.htm#JLR2-CH-9-SECT-4.1">Exceptions</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-1.8">Method Call Expression</A></h3>

<P CLASS=para>
<A NAME="CH04.CALL2"></A><A NAME="CH04.CALL"></A>A <I CLASS=emphasis>method call expression</I> is a primary
expression that invokes a method:


<p>
<img align=middle src="./figs/jlr0407.gif" alt="[Graphic: Figure from the text]" width=425 height=73 border=0>


<p>
<img align=middle src="./figs/jlr0408.gif" alt="[Graphic: Figure from the text]" width=425 height=74 border=0>

<P CLASS=para>
A method call expression
produces the pure value returned by the method; the type of this
value is specified by the return type in the method declaration.
But if the method has the return type <tt CLASS=literal>void</tt>,
the expression does not produce a value.

<P CLASS=para>
The <I CLASS=emphasis>PrimaryExpression</I>,
if present, is evaluated first. Then expressions provided as method
arguments are evaluated from left to right. Finally, the method
is invoked.

<P CLASS=para>
When a method call is made to a method that
is not <tt CLASS=literal>static</tt>, the call is made through an object
reference:
<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>If the method call expression does not contain
a <I CLASS=emphasis>PrimaryExpression</I> or <I CLASS=emphasis>ClassOrInterfaceName</I>
before the method name, the method call is made implicitly through
the object referenced by the keyword <tt CLASS=literal>this</tt>. This
form of a method call expression is treated as if it were written:

<DIV CLASS=screen>
<P>
<PRE>
this.Identifier(...)
</PRE>
</DIV>

<P>
<li CLASS=listitem>If the method call expression contains a <I CLASS=emphasis>PrimaryExpression</I>
before the method name, the call is made through the object reference
produced by the <I CLASS=emphasis>PrimaryExpression</I>.

<P>
<li CLASS=listitem>If the method call expression contains a
<I CLASS=emphasis>ClassOrInterfaceName</I>
before the method name, then the specified class must either be the same
class in which the method call expression appears or a superclass
of that class. In this case, the method call is made through the
object referenced by the keyword <tt CLASS=literal>this</tt>. This form
of a method call expression is treated as if it were written:

<DIV CLASS=screen>
<P>
<PRE>
((ClassOrInterfaceName)this).Identifier(...)
</PRE>
</DIV>

<P>
</UL>
<P CLASS=para>
When a method call is made to a <tt CLASS=literal>static</tt> method,
the call is made through a class or interface type:
<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>If
the method call expression does not contain a <I CLASS=emphasis>PrimaryExpression</I>
or <I CLASS=emphasis>ClassOrInterfaceName</I> before the method name,
the method call is made implicitly through the class that contains
the call.

<P>
<li CLASS=listitem>If the method call expression contains a
<I CLASS=emphasis>PrimaryExpression</I> before the method name, the
call is made through the class of the object reference produced
by the <I CLASS=emphasis>PrimaryExpression</I>.

<P>
<li CLASS=listitem>If the
method call expression contains a <I CLASS=emphasis>ClassOrInterfaceName</I>
before the method name, the method call is made through the specified
class or interface type.

<P>
</UL>
<P CLASS=para>
The rules for supplying actual
values for the formal parameters
of a method are similar to the rules for assignment. A particular
value can be specified as the actual value of a formal parameter
if and only if it is assignment-compatible with the type of the
formal parameter. You can use a type cast to make a value assignment
compatible with a formal parameter.

<P CLASS=para>
<A NAME="CH04.SELECT1"></A><A NAME="CH04.SELECT2"></A>The process that
the Java compiler uses to select the actual method that will be
invoked at runtime is rather involved. The compiler begins by finding
any methods that have the specified name. If the method call has
been made through an object reference, the compiler searches in
the class of that object reference. If the call has been made through
a specific class or interface name, the compiler searches in that
class or interface. The compiler searches all of the methods defined
in the particular class or interface, as well as any methods that
are inherited from superclasses or super-interfaces. At this point,
the compiler is searching for both <tt CLASS=literal>static</tt> and
non-<tt CLASS=literal>static</tt> methods, since it does not know which type of method is being called.

<P CLASS=para>
If the compiler finds more than one method, that means the method
is overloaded. Consider this example:

<DIV CLASS=screen>
<P>
<PRE>
public class MyMath {
    public int square(int x) { return x*x; }
    public long square(long x) { return x*x; }
    public float square(float x) { return x*x; }
    public double square(double x) { return x*x; }
    public double hypotenuse(double x, double y) {
        return Math.sqrt(x*x + y*y);
    }
}
</PRE>
</DIV>

<P CLASS=para>
In the above example,
the <tt CLASS=literal>square()</tt> method is overloaded,
while <tt CLASS=literal>hypotenuse()</tt> is not.

<P CLASS=para>
If the method is overloaded, the compiler then
determines which of the methods has formal parameters that are compatible
with the given arguments. If more than one method is compatible
with the given arguments, the method that most closely matches the
given parameters is selected. If the compiler cannot select one
of the methods as a better match than the others, the method selection
process fails and the compiler issues an error message. Note that
the return types of overloaded methods play no part in selecting
which method is to be invoked.

<P CLASS=para>
After the compiler successfully
selects the method that most closely matches the specified arguments,
it knows the name and signature of the method that will be invoked
at runtime. It does not, however, know for certain what class that
method will come from. Although the compiler may have selected a
method from <tt CLASS=literal>MyMath</tt>, it is possible that a subclass
of <tt CLASS=literal>MyMath</tt> could define a method that has the
same name and the same number and types of parameters as the selected
method. In this case, the method in the subclass overrides the method
in <tt CLASS=literal>MyMath</tt>. The compiler cannot know about overriding
methods, so it generates runtime code that dynamically selects the
appropriate method.

<P CLASS=para>
Here are the details of the three-step
method selection process:

<P>
<DL CLASS=variablelist>
<DT CLASS=varlistentry><I CLASS=emphasis>Step One</I><br>
<DD>

<P CLASS=para>
The method definitions are searched for methods
that, taken in isolation, could be called by the method call expression.
If the method call expression uses an object reference, the search
takes place in the class of that object reference. If the expression
uses a specific class or interface name, the search takes place
in that class or interface. The search includes all of the methods
defined in the particular class or interface, as well as any methods
inherited from superclasses or super-interfaces. The search
also includes both <tt CLASS=literal>static</tt> and non-<tt CLASS=literal>static</tt> methods.

<P CLASS=para>
A method is a candidate if it meets the following
criteria:
<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>The
name of the method is the same as the name specified in the method
call expression.

<P>
<li CLASS=listitem>The method is accessible to the method
call expression, based on any access modifiers specified in the
method's declaration.

<P>
<li CLASS=listitem>The number of formal parameters
declared for the method is the same as the number of actual arguments
provided in the method call expression.

<P>
<li CLASS=listitem>The data type
of each actual parameter is assignment-compatible with the corresponding
formal parameter.

<P>
</UL>
<P CLASS=para>
Consider the following expression that calls a method
defined in the preceding example:

<DIV CLASS=screen>
<P>
<PRE>
MyMath m;
m.square(3.4F)
</PRE>
</DIV>

<P CLASS=para>
Here is how the Java compiler uses the above criteria
to decide which method the expression actually calls:
<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>The name <tt CLASS=literal>square</tt> matches four methods defined in
the <tt CLASS=literal>MyMath</tt> class, so the compiler must decide
which one of those methods to invoke.

<P>
<li CLASS=listitem>All four methods
are declared <tt CLASS=literal>public</tt>, so they are all accessible
to the above expression and are thus all still viable candidates.

<P>
<li CLASS=listitem>The
method call expression provides one argument. Since the four methods
under consideration each take one argument, there are still four
possible choices.

<P>
<li CLASS=listitem>The method call expression is passing
a <tt CLASS=literal>float</tt> argument. Because a <tt CLASS=literal>float</tt>
value cannot be assigned to an <tt CLASS=literal>int</tt> or a <tt CLASS=literal>long</tt>
variable, the compiler can eliminate the versions of <tt CLASS=literal>square()</tt>
that take these types of arguments. That still leaves two possible
methods for the above expression: the version of <tt CLASS=literal>square()</tt>
that takes a <tt CLASS=literal>float</tt> argument and the one that
takes a <tt CLASS=literal>double</tt> argument.

<P>
</UL>
<p>
<DT CLASS=varlistentry><I CLASS=emphasis>Step Two</I><br>
<DD>

<P CLASS=para>
If more than one method meets the criteria in Step
One, the compiler tries to determine if one method is a more specific
match than the others. If there is no method that matches more specifically,
the selection process fails and the compiler issues an error message.

<P CLASS=para>
Given two methods, <tt CLASS=literal>A()</tt> and <tt CLASS=literal>B()</tt>,
that are both candidates to be invoked by the same method call expression,
<tt CLASS=literal>A()</tt> is more specific than <tt CLASS=literal>B()</tt> if:
<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>The class
in which the method <tt CLASS=literal>A()</tt> is declared is the same
class or a subclass of the class in which the method <tt CLASS=literal>B()</tt>
is declared.

<P>
<li CLASS=listitem>Each parameter of <tt CLASS=literal>A()</tt>
is assignment-compatible with the corresponding parameter of <tt CLASS=literal>B()</tt>.

<P>
</UL>
<P CLASS=para>
Let's go back to our previous example. We concluded
by narrowing the possible methods that the expression <tt CLASS=literal>m.square(3.4F)</tt>
might match to the methods in <tt CLASS=literal>MyMath</tt> named <tt CLASS=literal>square()</tt>
that take either a <tt CLASS=literal>float</tt> or a <tt CLASS=literal>double</tt>
argument. Using the criteria of this step, we can further narrow
the possibilities. These methods are declared in the same class,
but the version of <tt CLASS=literal>square()</tt> that takes a <tt CLASS=literal>float</tt>
value is more specific than the one that takes a <tt CLASS=literal>double</tt>
value. It is more specific because a <tt CLASS=literal>float</tt> value
can be assigned to a <tt CLASS=literal>double</tt> variable, but a <tt CLASS=literal>double</tt>
value cannot be assigned to a <tt CLASS=literal>float</tt> variable
without a type cast.

<P CLASS=para>
There are some cases in which it is not possible
to choose one method that is more specific than others. When this
happens, the Java compiler treats the situation as an error and
issues an appropriate error message. 

<P CLASS=para>
For example, consider a situation
where the compiler needs to choose between two methods declared
as follows:

<DIV CLASS=screen>
<P>
<PRE>
double foo(float x, double y)
double foo(double x, float y)
</PRE>
</DIV>

<P CLASS=para>
Neither method is more specific than the other.
The first method is not more specific because the type of its second
parameter is <tt CLASS=literal>double</tt> and <tt CLASS=literal>double</tt>
values cannot be assigned to <tt CLASS=literal>float</tt> variables.
The second method is not more specific because of a similar problem
with its first parameter.

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>Step Three</I><br>
<DD>

<P CLASS=para>
After successfully completing the previous two steps,
the Java compiler knows that the expression in our example will
call a method named <tt CLASS=literal>square()</tt> and that the method
will take one <tt CLASS=literal>float</tt> argument. However, the compiler
does not know if the method called at runtime will be the one defined
in the <tt CLASS=literal>MyMath</tt> class. It is possible that a subclass
of <tt CLASS=literal>MyMath</tt> could define a method that is also
called <tt CLASS=literal>square()</tt> and takes a single <tt CLASS=literal>float</tt>
argument. This method in a subclass would override the method in
<tt CLASS=literal>MyMath</tt>. If the variable <tt CLASS=literal>m</tt>
in the expression <tt CLASS=literal>m.square(3.4F)</tt> refers to such
a subclass, the method defined in the subclass is called instead
of the one defined in <tt CLASS=literal>MyMath</tt>.

<P CLASS=para>
The Java compiler generates code to determine at
runtime which method named <tt CLASS=literal>square()</tt> that takes
a single <tt CLASS=literal>float</tt> argument it should call. The Java
compiler must always generate such runtime code for method call
expressions, unless it is able to determine at compile time the
exact method to be invoked at runtime.

<P CLASS=para>
There are four cases in which the compiler can know
exactly which method is to be called at runtime:
<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>The method is called through an object reference, and the type of the
reference is a <tt CLASS=literal>final</tt> class. Since the type of
the reference is a <tt CLASS=literal>final</tt> class, Java does not
allow any subclasses of that class to be defined. Therefore,
the object reference will always refer to an object of the class
declared <tt CLASS=literal>final</tt>. The Java compiler knows the actual
class that the reference will refer to, so it can know the actual method
to be called at runtime.

<P>
<li CLASS=listitem>The method is invoked through
an object reference, and the type of the reference is a class that
defines or inherits a <tt CLASS=literal>final</tt> method that has the
method name, number of parameters, and types of parameters determined
by the preceding steps. In this case, the compiler knows the actual
method to be called at runtime because <tt CLASS=literal>final</tt>
methods cannot be overridden.

<P>
<li CLASS=listitem>The method is a <tt CLASS=literal>static</tt>
method. When a method is declared static, it is also implicitly
declared final. Thus, the compiler can be sure that the method to
be called at runtime is the one defined in or inherited by the specified
class that has the method name, number of parameters, and types
of parameters determined by the preceding steps.

<P>
<li CLASS=listitem>The
compiler is able to deduce that a method is invoked through an object
reference that will always refer to the same class of object at
runtime. One way the compiler might deduce this is through
data flow analysis.

<P>
</UL>
<P CLASS=para>
If none of the above cases applies to a method
call expression, the Java compiler must generate runtime code to
determine the actual method to be invoked. The runtime selection
process begins by getting the class of the object through which
the method is being invoked. This class is searched for a method
that has the same name and the same number and types of parameters
as the method selected in Step Two. If this class does not contain
such a definition, its immediate superclass is searched. If the
immediate superclass does not contain an appropriate definition,
its superclasses are searched, and so on up the inheritance hierarchy.
This search process is called <I CLASS=emphasis>dynamic method lookup</I>.

<P CLASS=para>
Dynamic method lookup always begins with the class
of the actual object being referenced. The type of the reference
being used to access the object does not influence where the search
for a method begins. The one exception to this rule occurs when
the keyword <tt CLASS=literal>super</tt> is used as part of the method
call expression. The form of this type
of method call expression is:

<DIV CLASS=screen>
<P>
<PRE>
super.Identifier(...)
</PRE>
</DIV>

<P CLASS=para>
In this case, dynamic method lookup begins by searching
the superclass of the class that the calling code appears in.</DL>
<P CLASS=para>
Now
that we've gone through the entire method selection process, let's
consider an example that illustrates the process:

<DIV CLASS=screen>
<P>
<PRE>
class A {}
class B extends A {}
class C extends B {}
class D extends C {}
class W {
    void foo(D d) {System.out.println("C");}
}
class X extends W {
    void foo(A a) {System.out.println("A");}
    void foo(B b) {System.out.println("X.B");}
}
class Y extends X {
    void foo(B b) {System.out.println("Y.B");}
}
class Z extends Y {
    void foo(C c) {System.out.println("D");}
}
public class CallSelection {
    public static void main(String [] argv) {
        Z z = new Z();
        ((X) z).foo(new C());
    }
}
</PRE>
</DIV>

<P CLASS=para>
In the class <tt CLASS=literal>CallSelection</tt>, the method
<tt CLASS=literal>main()</tt>
contains a call to a method named <tt CLASS=literal>foo()</tt>. This
method is called through an object reference. Although the object
refers to an instance of the class <tt CLASS=literal>Z</tt>, it is treated
as an instance of the class <tt CLASS=literal>X</tt> because the reference
is type cast to the class <tt CLASS=literal>X</tt>. The process of selecting
which method to call proceeds as follows:
<P>
<OL CLASS=orderedlist>
<li CLASS=listitem>The compiler
finds all of the methods named <tt CLASS=literal>foo()</tt> that are
accessible through an object of class <tt CLASS=literal>X</tt>: <tt CLASS=literal>foo(A)</tt>,
<tt CLASS=literal>foo(B)</tt>, and <tt CLASS=literal>foo(D)</tt>. However,
because a reference to an object of class <tt CLASS=literal>C</tt> cannot
be assigned to a variable of class <tt CLASS=literal>D</tt>, <tt CLASS=literal>foo(D)</tt>
is not a candidate to be invoked by the method call expression.

<P>
<li CLASS=listitem>Now the compiler must choose one of the two remaining
<tt CLASS=literal>foo()</tt> methods as more specific than the other.
Both methods are defined in the same class, but <tt CLASS=literal>foo(B)</tt>
is more specific than <tt CLASS=literal>foo(A)</tt> because a reference
to an object of class <tt CLASS=literal>B</tt> can be assigned to a
variable declared with a type of class <tt CLASS=literal>A</tt>.

<P>
<li CLASS=listitem>At runtime, the dynamic method lookup process finds
that it has a reference to an object of class <tt CLASS=literal>Z</tt>.
The fact that the reference is cast to class <tt CLASS=literal>X</tt>
is not significant, since dynamic lookup is concerned with the class
of an object, not the type of the reference used to access the object.
The definition of class <tt CLASS=literal>Z</tt> is searched for a method
named <tt CLASS=literal>foo()</tt> that takes one parameter that is
a reference to an object of class <tt CLASS=literal>B</tt>. No such
method is found in the definition of class <tt CLASS=literal>Z</tt>,
so its immediate superclass, class <tt CLASS=literal>Y</tt>, is searched.
Such a method is found in class <tt CLASS=literal>Y</tt>, so that method
is invoked.

<P>
</OL>
<P CLASS=para>
Here is another example that
shows some ambiguous and erroneous method call expressions:

<DIV CLASS=screen>
<P>
<PRE>
class A {}
class B extends A {}
class AmbiguousCall {
    void foo(B b, double x){}
    void foo(A a, int i){}
    void doit() {
        foo(new A(), 8);   // Matches foo(A, int)
        foo(new A(), 8.0); // Error: doesn't match anything
        foo(new B(), 8);   // Error: ambiguous, matches both
        foo(new B(), 8.0); // Matches foo(B, double)
    }
}
</PRE>
</DIV>

<P CLASS=para>
<b>References</b>
<A HREF="ch04_13.htm#JLR2-CH-4-SECT-13.1">Assignment Compatibility</A>;
<I CLASS=emphasis>ClassOrInterfaceName</I> 4.1.6;
<A HREF="ch04_04.htm#JLR2-CH-4-SECT-4.5">Casts</A>;
<I CLASS=emphasis>Expression</I> 4;
<A HREF="ch02_02.htm#JLR2-CH-2-SECT-2.1">Identifiers</A>;
<A HREF="ch05_03.htm#JLR2-CH-5-SECT-3.5">Inheritance</A>;
<A HREF="ch05_05.htm#JLR2-CH-5-SECT-5.4.2">Interface Methods</A>;
<A HREF="ch05_04.htm#JLR2-CH-5-SECT-4.4.2">Methods</A>;
<A HREF="ch04_01.htm#JLR2-CH-4-SECT-1">Primary Expressions</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-1.9">Class Literals</A></h3>

<P CLASS=para>
A <I CLASS=emphasis>class literal</I> 
is an expression that produces a reference to a 
<tt CLASS=literal>Class</tt> object that identifies a specified data 
type. Class literals are not supported prior to Java 1.1. 
Here's the syntax for a class literal:


<p>
<img align=middle src="./figs/jlr0409.gif" alt="[Graphic: Figure from the text]" width=450 height=131 border=0>

<P CLASS=para>
If the type in a class literal is a reference type, the class literal
produces a reference to the <tt CLASS=literal>Class</tt> object that 
defines the specified reference type. The following are some examples of
this type of class literal:

<DIV CLASS=screen>
<P>
<PRE>
String.class
java.util.Stack.class
myNewClass.class
</PRE>
</DIV>

<P CLASS=para>
Such a class literal 
can throw a <tt CLASS=literal>NoClassDefFoundError</tt> if the specified
class is not available.

<P CLASS=para>
You can also call <tt CLASS=literal>Class.forName()</tt> with the name of a
specified reference type to retrieve the <tt CLASS=literal>Class</tt> object
for that type. For example:

<DIV CLASS=screen>
<P>
<PRE>
Class.forName("java.util.Stack")
</PRE>
</DIV>

<P CLASS=para>
A class literal and a call to 
<tt CLASS=literal>Class.forName()</tt> for the same reference type return
the same <tt CLASS=literal>Class</tt> object. There are certain
situations when it makes sense to use a class literal, while in other
cases a call to <tt CLASS=literal>Class.forName()</tt> is more appropriate.
Here are the differences between the two techniques for retrieving
a <tt CLASS=literal>Class</tt> object:

<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>A class literal cannot contain an expression, so it 
always refers to the same type. However, the argument passed to
<tt CLASS=literal>Class.forName()</tt> can be an 
expression that produces different strings that name different classes.

<P>
<li CLASS=listitem>The class or interface name passed to
<tt CLASS=literal>Class.forName()</tt> must be fully qualified by its
package name. The class or interface name in a class literal, however,
does not typically need to include a package name because the Java
compiler can use information provided in package and import directives
to deduce the package name.

<P>
<li CLASS=listitem>The name of an inner class can be used directly with a class literal.
Because of the way that inner-class names are encoded, however, 
when an inner-class name is passed to <tt CLASS=literal>Class.forName()</tt>, 
the name must contain dollar signs (<tt CLASS=literal>$</tt>) 
in place of dots (<tt CLASS=literal>.</tt>).

<P>
<li CLASS=listitem>The efficiency of a class literal is comparable to a field reference; it
is more efficient than the method call required by 
<tt CLASS=literal>Class.forName()</tt>.

<P>
</UL>
<P CLASS=para>
If the type in a class literal is <tt CLASS=literal>void</tt> 
or a primitive type, the class literal produces a reference to a 
unique <tt CLASS=literal>Class</tt> object that 
represents <tt CLASS=literal>void</tt> or the specified type. 
The special 
<tt CLASS=literal>Class</tt> object that represents <tt CLASS=literal>void</tt> 
or a primitive type can be distinguished from a <tt CLASS=literal>Class</tt>
object that represents a reference type by calling its 
<tt CLASS=literal>isPrimitive()</tt> method. This method only returns
<tt CLASS=literal>true</tt> if the <tt CLASS=literal>Class</tt>
object represents <tt CLASS=literal>void</tt> or a primitive type. 
The <tt CLASS=literal>getName()</tt> method of a special <tt CLASS=literal>Class</tt> 
object returns a string that contains the name of the primitive type 
represented by the object. The easiest way to determine the
primitive type of a special <tt CLASS=literal>Class</tt> object is
to compare it to the <tt CLASS=literal>TYPE</tt> variables of the 
primitive wrapper classes.
The following comparisons always produce <tt CLASS=literal>true</tt>:

<DIV CLASS=screen>
<P>
<PRE>
boolean.class == Boolean.TYPE
byte.class == Byte.TYPE
short.class == Short.TYPE
int.class == Integer.TYPE
long.class == Long.TYPE
char.class == Character.TYPE
float.class == Float.TYPE
double.class == Double.TYPE
void.class == Void.TYPE
</PRE>
</DIV>

<P CLASS=para>
<b>References</b>
<A HREF="ch10_01.htm">Boolean</A>;
<A HREF="ch10_02.htm">Byte</A>;
<A HREF="ch10_03.htm">Character</A>;
<A HREF="ch10_04.htm">Class</A>;
<A HREF="ch10_08.htm">Double</A>;
<A HREF="ch09_04.htm#JLR2-CH-9-SECT-4.2">Errors</A>;
<A HREF="ch10_09.htm">Float</A>;
<A HREF="ch05_03.htm#JLR2-CH-5-SECT-3.7">Inner Classes</A>;
<A HREF="ch10_10.htm">Integer</A>;
<A HREF="ch10_11.htm">Long</A>;
<A HREF="ch10_19.htm">Short</A>;
<A HREF="ch10_26.htm">Void</A>;
<I CLASS=emphasis>Type</I> 3

</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch03_02.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch04_02.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Reference Types</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>Allocation Expressions</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
